package com.code.webshopapp;

import java.util.ArrayList;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;
import at.codebase.core.FeedbackData;
import at.codebase.core.search.ItemSearchResultInfo;
import at.codebase.db.entities.EItemFeedback;
import at.codebase.web.util.json.JsonDecoder;

public class StartSeite extends Activity {

	private static ArrayList<String> title = new ArrayList<String>();
	private static ArrayList<String> imageUrl = new ArrayList<String>();
	private static ArrayList<Double> rating = new ArrayList<Double>();
	private static ArrayList<Long> createTime = new ArrayList<Long>();
	private static ArrayList<Double> price = new ArrayList<Double>();
	private static ArrayList<String> description = new ArrayList<String>();
	private static ArrayList<String> feedback = new ArrayList<String>();

	// / just fun
	private static ArrayList<String> urls = new ArrayList<String>();
	//

	private static int lfdRowId = 0;
	private EditText suchFeld;
	private OnClickListener rowListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			Intent intent = new Intent(getApplicationContext(),
					DetailSeite.class);
			intent.putExtra("id", arg0.getId());
			intent.putExtra("imageUrl", imageUrl.get(arg0.getId()));
			intent.putExtra("title", title.get(arg0.getId()));
			intent.putExtra("rating", rating.get(arg0.getId()));
			intent.putExtra("createTime", createTime.get(arg0.getId()));
			intent.putExtra("price", price.get(arg0.getId()));
			intent.putExtra("description", description.get(arg0.getId()));
			intent.putExtra("feedback", feedback.get(arg0.getId()));

			startActivity(intent);
		}
	};
	private View viewTableLayout;
	private ImageCache imageCache;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_start_seite);

		// ////// Caching
		final int cacheSize = (int) ((Runtime.getRuntime().maxMemory() / 1024)) / 8;
		imageCache = new ImageCache(cacheSize);
		// ////////

		// //////
		urls.add("http://www.atemenergie.at/img/bluete_pic.png");
		urls.add("https://lh6.googleusercontent.com/-n-yhavhJEwo/AAAAAAAAAAI/AAAAAAAAAGE/5h_YKxSaXxE/s250-c-k/photo.jpg");
		urls.add("http://global3.memecdn.com/i-farted_o_588265.jpg");
		urls.add("http://farts.typepad.com/photos/uncategorized/cat_fart.jpg");
		urls.add("http://www.moviefancentral.com/images/pictures/review74591/postal-cat.jpg?1356361073");
		// /////

		viewTableLayout = findViewById(R.id.startSeiteTableLayout);

		TextView login = (TextView) findViewById(R.id.startSeiteLoginTextView);
		login.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				Intent intent = new Intent(getApplicationContext(), Login.class);
				startActivity(intent);
			}
		});

		suchFeld = (EditText) findViewById(R.id.startSeiteSuchFeld);
		Button suchButton = (Button) findViewById(R.id.startSeiteSuchButton);
		suchButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (!suchFeld.getText().toString().equals("")) {
					try {

						String queryResult = new HttpRequest()
								.execute(
										"https://project-buybase.appspot.com/ajax/searchProvider",
										"query", suchFeld.getText().toString())
								.get();
						ItemSearchResultInfo res = JsonDecoder
								.decodeItemSearchResultInfo(queryResult);

						// alte Liste löschen
						title.clear();
						imageUrl.clear();
						rating.clear();
						createTime.clear();
						price.clear();
						description.clear();
						feedback.clear();
						((ViewGroup) viewTableLayout).removeAllViews();
						lfdRowId = 0;

						String titleAdd;
						String imageUrlAdd;
						double ratingAdd;
						long createTimeAdd;
						double priceAdd;
						String descriptionAdd;
						String feedbackAdd = "";

						if (res.getCount() == 0) {
							Toast.makeText(getApplicationContext(),
									"No articles were found...",
									Toast.LENGTH_SHORT).show();
						}

						for (int i = 0; i < res.getCount(); i++) {
							titleAdd = res.getResults().get(i).getItem()
									.getTitle();
							// imageUrlAdd = res.getResults().get(i).getItem()

							createTimeAdd = res.getResults().get(i).getItem()
									.getTimeCreate();
							priceAdd = res.getResults().get(i).getItem()
									.getPrice();
							descriptionAdd = res.getResults().get(i).getItem()
									.getDescription();

							long productID = res.getResults().get(i).getItem()
									.getId();
							String queryRatingFeedback = new HttpRequest()
									.execute(
											"https://project-buybase.appspot.com/ajax/feedbackProvider",
											"itemId", String.valueOf(productID))
									.get();
							// FeedbackData feedBData = JsonDecoder.decodeFeedbacks(queryRatingFeedback);

							feedbackAdd = "default Feedback";
							ratingAdd = 2.0;
							/*
							ratingAdd = feedBData.getRatingAverage();
							
							 * for (EItemFeedback feed :
							 * feedBData.getItemFeedbackList()) { feedbackAdd +=
							 * feed.getFeedbackContent(); }
							 */

							addProduct(titleAdd,
									urls.get(lfdRowId % urls.size()),
									ratingAdd, createTimeAdd, priceAdd,
									descriptionAdd, feedbackAdd);
						}

					} catch (Exception e) {

						String s = "";
						StackTraceElement[] st = e.getStackTrace();
						for (StackTraceElement strace : st) {
							s += strace.toString();
						}

						Toast.makeText(
								getApplicationContext(),
								"An error occurred while loading the search results..."
										+ s, Toast.LENGTH_LONG).show();
					}
				}
			}
		});

	}

	public void addProduct(String titleP, String imageUrlP, double ratingP,
			long createTimeP, double priceP, String descriptionP,
			String feedbackP) {
		TableRow row = new TableRow(this);
		row.setId(lfdRowId++);
		row.setGravity(Gravity.CENTER_VERTICAL);

		ImageView image = new ImageView(this);
		TextView text1 = new TextView(this);
		TextView text2 = new TextView(this);

		if (imageCache.getBitmapFromMemCache(imageUrlP) != null) {
			image.setImageBitmap(imageCache.getBitmapFromMemCache(imageUrlP));
			// descriptionP += " ... wurde aus Cache geladen xD ..";
		} else {
			try {
				Bitmap bmp = new ImageDownloader().execute(imageUrlP).get();
				image.setImageBitmap(bmp);
				imageCache.addBitmapToMemoryCache(imageUrlP, bmp);
				// image.setScaleType(ScaleType.FIT_XY);
			} catch (Exception e) {
			}
		}

		image.setLayoutParams(new TableRow.LayoutParams(150, 90));
		image.setPadding(0, 0, 0, 20);

		row.addView(image);

		text1.setText(titleP);
		text1.setTextSize(20);
		TableRow.LayoutParams param = new TableRow.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1);
		param.setMargins(5, 0, 5, 0);
		text1.setLayoutParams(param);
		text1.setTextSize(15);
		text1.setGravity(Gravity.CENTER);
		row.addView(text1);

		text2.setText(priceP + " $");
		text2.setLayoutParams(new TableRow.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		text2.setGravity(Gravity.RIGHT);
		text2.setTextSize(18);
		text2.setPadding(0, 0, 20, 0);
		row.addView(text2);

		row.setOnClickListener(rowListener);
		((ViewGroup) viewTableLayout).addView(row);

		title.add(titleP);
		imageUrl.add(imageUrlP);
		rating.add(ratingP);
		createTime.add(createTimeP);
		price.add(priceP);
		description.add(descriptionP);
		feedback.add(feedbackP);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_start_seite, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menuBeenden) {
			finish();
		}
		if (item.getItemId() == R.id.menuLogin) {
			Intent intent = new Intent(getApplicationContext(), Login.class);
			startActivity(intent);
		}

		return true;
	}

}
